package accs.model.mail;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class MailSettingsFetcher {
	public MailSettingsFetcher() {
	}
	
	public static String extractHost(String email) {
		return email.substring(email.indexOf("@")+1);
	}
	
	public List<Properties> fetchSettingsForAddress(String host) {
		MyHandler handler=new MyHandler();
		
		try {
			XMLReader reader=XMLReaderFactory.createXMLReader();
			
			reader.setContentHandler(handler);
			
			URL url=new URL("https://autoconfig-live.mozillamessaging.com/autoconfig/v1.1/"+extractHost(host));
			InputStream is=url.openStream();
			
			reader.parse(new InputSource(is));
			
			is.close();
		} catch(Exception e) {
			//e.printStackTrace();
			return null;
		}
		
		return handler.getProperties();
	}
	
	private class MyHandler extends DefaultHandler {
		private List<Properties> propertyList=new ArrayList<Properties>();
		private Properties props;
		private String currentProp;
		private String currentValue;
		
		public List<Properties> getProperties() {
			return propertyList;
		}
		
		public void startElement (String uri, String name, String qName, Attributes atts) {
			if(qName.equals("incomingServer")) {
				props=new Properties();
				props.setProperty("type",atts.getValue("type"));
			} else {
				if(props!=null) {
					currentValue="";
					currentProp=qName;
				}
			}
		}
		
		public void endElement (String uri, String name, String qName) {
			if(qName.equals("incomingServer")) {
				propertyList.add(props);
				props=null;
			} else {
				if(props!=null) {
					if(currentProp.equals("hostname")) {
						props.setProperty("host",currentValue);
					} else if(currentProp.equals("port")) {
						props.setProperty("port",currentValue);
					} else if(currentProp.equals("socketType")) {
						if(currentValue.equals("SSL")) {
							props.setProperty("type", props.getProperty("type")+"s");
						}
					}
				}
			}
	    }
		
		public void characters (char ch[], int start, int length) {
			currentValue+=new String(ch,start,length);
		}
	}
	
//	public static void main(String[] args) {
//		List<Properties> list=new MailSettingsFetcher().fetchSettingsForAddress("test@yahoo.com");
//		
//		for(Properties props: list) {
//			System.out.println(props);
//		}
//	}
}